/**
Sprite.cpp
Title: Binge Sprite Program File
Descr: Sprite Class

Copyright (c) 2010, Brant Ryan Anderson
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <ORGANIZATION> nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/

#include "../../binge/objects/Sprite.hpp"

namespace binge {

Sprite::Sprite()
{
	AnimationSet tmp;
	addAnimSet(tmp);

	image = 0;
	imageLoaded = false;
	setPosition(0.0f,0.0f);
	setVelocity(0.0f,0.0f);
	state = 0;
	direction = 0;
	width = 1;
	height = 1;
	curframe = 0;
	totalframes = 1;
	animcolumns = 1;
	framestart = 0;
	frametimer = 0;
	faceAngle = 0;
	moveAngle = 0;
	movetimer = 16;
	movestart = 0;
}

Sprite::~Sprite()
{
	if (imageLoaded && image != 0)
	{
		delete image;
		image = 0;
	}
}

bool
Sprite::loadImage(std::string filename, sf::Color transcolor)
{
	// if image already exists, free it
	if (imageLoaded && image != 0)
	{
		delete image;
		image = 0;
	}

	// create texture and load image
	image = new Texture();
	if (image->Load(filename, transcolor))
	{
		setWidth(image->getWidth());
		setHeight(image->getHeight());

        // Collision Rectangle
        setColRectOffsetX(0);
        setColRectOffsetY(0);
        setColRectWidth(getWidth());
        setColRectHeight(getHeight());

        collisionRect.Left = static_cast<double>(getX())+getColRectOffsetX();
        collisionRect.Top = static_cast<double>(getY())+getColRectOffsetY();
        collisionRect.Right = 	static_cast<double>(getX()) + getColRectOffsetX() +
                                                    getColRectWidth()*getScale();
        collisionRect.Bottom = 	static_cast<double>(getY()) + getColRectOffsetY() +
                                                    getColRectHeight()*getScale();

		imageLoaded = true;
		return true;
	} else { return false; }
}

void
Sprite::setImage(Texture* tex)
{
	image = tex;
	setWidth(tex->getWidth());
	setHeight(tex->getHeight());

	// Collision Rectangle
	setColRectOffsetX(0);
	setColRectOffsetY(0);
	setColRectWidth(getWidth());
	setColRectHeight(getHeight());

	collisionRect.Left = static_cast<double>(getX())+getColRectOffsetX();
	collisionRect.Top = static_cast<double>(getY())+getColRectOffsetY();
	collisionRect.Right = 	static_cast<double>(getX()) + getColRectOffsetX() +
												getColRectWidth()*getScale();
	collisionRect.Bottom = 	static_cast<double>(getY()) + getColRectOffsetY() +
												getColRectHeight()*getScale();

	imageLoaded = false;
}

void
Sprite::draw()
{
	int animrows = getTotalFrames() / animcolumns;
	int frameWidth = getWidth() / animcolumns;
	int frameHeight = getHeight() / animrows;

	float fx = ((curframe % animcolumns) * (width / animcolumns)) / static_cast<float>(getWidth());
	float fy = ((curframe / animcolumns) * (height / animrows)) / static_cast<float>(getHeight());
	float fw = frameWidth / static_cast<float>(getWidth());
	float fh = frameHeight / static_cast<float>(getHeight());

	GLfloat box[] = {	getX(),getY(),
						(frameWidth*getScale())+getX(),getY(),
						(frameWidth*getScale())+getX(),(frameHeight*getScale())+getY(),
						getX(),(frameHeight*getScale())+getY()	};
	GLfloat tex[] = {	fx,fy,
						fx+fw,fy,
						fx+fw,fy+fh,
						fx,fy+fh	};

	//Bind texture
	if (prevTexture != image->getTexture())
	{
		glBindTexture(GL_TEXTURE_2D, image->getTexture());
		prevTexture = image->getTexture();
	}

	// Enable Arrays
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	// Set Pointers
	glVertexPointer(2, GL_FLOAT, 0, box);
	glTexCoordPointer(2, GL_FLOAT, 0, tex);
	// Draw Quad
	glDrawArrays(GL_QUADS, 0, 4);
	// Disable Arrays
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);

	glFinish();
}

void
Sprite::move()
{
	if (movetimer > 0) {

		if (lifetimeTimer.getTimer() > movestart + movetimer) {
			//reset move timer
			movestart = lifetimeTimer.getTimer();

			//move sprite by velocity amount
			this->setX(this->getX() + this->getVelocity().getX());
			this->setY(this->getY() + this->getVelocity().getY());
		}
	}
	else {
		//no movement timer--update at cpu clock speed
		this->setX(this->getX() + this->getVelocity().getX());
		this->setY(this->getY() + this->getVelocity().getY());
	}
	//update the collision rectangle
	collisionRect.Left = static_cast<double>(getX())+getColRectOffsetX();
	collisionRect.Top = static_cast<double>(getY())+getColRectOffsetY();
	collisionRect.Right = 	static_cast<double>(getX()) + getColRectOffsetX() +
												(getColRectWidth()*getScale());
	collisionRect.Bottom = 	static_cast<double>(getY()) + getColRectOffsetY() +
												(getColRectHeight()*getScale());
}

void
Sprite::animate(void)
{
	int set = 0;
	for (unsigned int x = 0; x < animSetList.size(); x++)
	{
		if (animSetList[x].getName() == getAnimName())
		{
			set = x;
			x = animSetList.size();
		}
	}
	curframe = animSetList[set].getCurrentFrame();
	frametimer = animSetList[set].getFrameTimer();
	//update frame based on animdir
	if (frametimer > 0) {

		if (lifetimeTimer.getTimer() > framestart + frametimer)  {
			//reset animation timer
			framestart = lifetimeTimer.getTimer();
			animSetList[set].NextFrame();
		}
	}
	else {
		//no animation timer--update at cpu clock speed
		animSetList[set].NextFrame();
	}
}

int
Sprite::getFrameWidth(void)
{
	int frameWidth = getWidth() / animcolumns;

    return frameWidth;
}

int
Sprite::getFrameHeight(void)
{
	int animrows = getTotalFrames() / animcolumns;
	int frameHeight = getHeight() / animrows;

	return frameHeight;
}

} // namespace
